package com.bifrost.admin.controller;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.common.base.ServerResponse;
import com.bifrost.entity.Coupon;
import com.bifrost.entity.CouponDetail;
import com.bifrost.entity.MerchantStore;
import com.bifrost.model.ResultModel;
import com.bifrost.model.coupon.WXCouponDetailRO;
import com.bifrost.model.coupon.WXCouponDetailVO;
import com.bifrost.model.coupon.WXCouponTotalRO;
import com.bifrost.model.coupon.WXCouponTotalVO;
import com.bifrost.model.ro.coupon.CouponDetailFilterRO;
import com.bifrost.model.ro.coupon.CouponFilterRO;
import com.bifrost.model.ro.coupon.CouponRO;
import com.bifrost.model.ro.coupon.CouponTypeRO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.model.vo.coupon.CouponDetailVO;
import com.bifrost.model.vo.coupon.CouponVO;
import com.bifrost.repository.MerchantStoreRepository;
import com.bifrost.repository.OrderItemRepository;
import com.bifrost.repository.OrderRepository;
import com.bifrost.service.AdminCouponService;
import com.bifrost.service.AdminUserService;
import com.bifrost.util.BeanValidator;
import com.bifrost.util.ExcelReportUtils;
import com.bifrost.util.QueryUtils;
import com.bifrost.util.TransformUtils;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author rangf
 * @date 2018/5/7
 */
@RestController
@RequestMapping("/admin/coupon")
public class AdminCouponController {

    private Logger LOGGER = LoggerFactory.getLogger(AdminCouponController.class);

    @Autowired
    AdminCouponService adminCouponService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    OrderItemRepository orderItemRepository;
    @Autowired
    OrderRepository orderRepository;

    /*
    @ApiOperation("优惠券类型列表")
    @GetMapping("/type/list")
    public ServerResponse listType(@CurrentAdmin User user) {
        List<CouponTypeRO> roList = adminCouponService.listCouponType(user);
        if (CollectionUtils.isNotEmpty(roList)) {
            return ServerResponse.createBySuccess(roList);
        }
        return ServerResponse.createByErrorMsg("没有数据");
    }
    */

    @ApiOperation("优惠券类型添加")
    @PostMapping("/type/add")
    public ServerResponse addType(@CurrentAdmin Long userId, @RequestBody CouponTypeRO ro) {
        Map<String, String> errors = BeanValidator.validate(ro);
        if (!errors.isEmpty())
            return ServerResponse.createByError(errors.values());
        ro.setCouponTypeId(null);
        return adminCouponService.addCouponType(userService.findById(userId) , ro);
    }

    @ApiOperation("优惠券类型更新")
    @PostMapping("/type/update")
    public ServerResponse updateType(@CurrentAdmin Long userId, @RequestBody CouponTypeRO ro) {
        Map<String, String> errors = BeanValidator.validate(ro);
        if (!errors.isEmpty())
            return ServerResponse.createByError(errors.values());
        return adminCouponService.updateCouponType(userService.findById(userId) , ro);
    }

    @ApiOperation("优惠券类型删除")
    @PostMapping("/type/delete")
    public ServerResponse deleteType(@RequestParam(value = "couponTypeIds[]") Long[] couponTypeIds) {
        return adminCouponService.deleteCouponType(couponTypeIds);
    }

    //优惠券不再与门店关联，故不可通过门店查询
    @ApiOperation("优惠券列表")
    @PostMapping("/list")
    public ServerResponse list(@CurrentAdmin Long userId, @RequestBody CouponFilterRO ro) {
        /*
        MerchantStore merchantStore = user.getMerchantStore();
        if (merchantStore != null) {
            PageVO<CouponVO> pageVO = adminCouponService.listCoupon(merchantStore, ro);
            if (pageVO == null)
                return ServerResponse.createByErrorMsg("没有数据");
            return ServerResponse.createBySuccess(pageVO);
        }
        return ServerResponse.createByErrorMsg("没有数据");
        */
        List<Long> merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId),ro.getMerchantStoreIds());
        MerchantStore merchantStore = null;
        PageVO<CouponVO> pageVO = adminCouponService.listCoupon(merchantStore, ro,merchantStoreIdList);
        if (pageVO == null)
            return ServerResponse.createByErrorMsg("没有数据");
        return ServerResponse.createBySuccess(pageVO);
    }

    @ApiOperation("优惠券添加")
    @PostMapping("/add")
    public ServerResponse add(@CurrentAdmin Long userId, @RequestBody CouponRO ro) {
        Map<String, String> errors = BeanValidator.validate(ro);
        if (!errors.isEmpty())
            return ServerResponse.createByError(errors.values());
        ro.setCouponId(null);
        return adminCouponService.addCoupon(userService.findById(userId) , ro);
    }

    @ApiOperation("优惠券审核[批量]:已废弃")
    @Deprecated
    @PostMapping("/auth/batch")
    public ServerResponse authBatch(@CurrentAdmin Long userId, @RequestParam(value = "couponIds[]") Long[] couponIds) {
        if (couponIds != null && couponIds.length >= 1)
            return adminCouponService.authBatchCoupon(userService.findById(userId) , couponIds);
        return ServerResponse.createByErrorMsg("请选择需要审核的优惠券");
    }

    @ApiOperation("优惠券审核/下架")
    @PostMapping("/auth")
    public ServerResponse auth(@CurrentAdmin Long userId,
                               @RequestParam(value = "couponId") Long couponId,
                               @RequestParam(value = "authType") String authType) {
            return adminCouponService.auth(userService.findById(userId) , couponId, authType);
    }

    @ApiOperation("优惠券更新")
    @PostMapping("/update")
    public ServerResponse update(@CurrentAdmin Long userId, @RequestBody CouponRO ro) {
        return adminCouponService.updateCoupon(userService.findById(userId) , ro);
    }

    @ApiOperation("优惠券删除")
    @PostMapping("/delete")
    public ServerResponse delete(@RequestParam(value = "couponIds[]") Long[] couponIds) {
        if (couponIds != null && couponIds.length >= 0)
            return adminCouponService.deleteCoupon(couponIds);
        return ServerResponse.createByErrorMsg("请选择需要要删除的优惠券");

    }

    @ApiOperation("优惠券明细")
    @PostMapping("/detail/list")
    public ServerResponse listDetail(@RequestBody CouponDetailFilterRO ro) {
        Map<String, String> errors = BeanValidator.validate(ro);
        if (!errors.isEmpty())
            return ServerResponse.createByError(errors.values());
        Page<CouponDetail> data = adminCouponService.listCouponDetail(ro);
        if (data != null && data.hasContent()) {
            List<CouponDetail> couponDetailList = data.getContent();
            if (CollectionUtils.isNotEmpty(couponDetailList)) {
                List<CouponDetailVO> couponDetailVOList = new ArrayList<>();
                for (CouponDetail couponDetail : couponDetailList) {
                    couponDetailVOList.add(TransformUtils.transformToCouponDetailVO(couponDetail));
                }
                PageVO<CouponDetailVO> pageVO = new PageVO<>
                        (ro.getPage(), ro.getPageSize(), (int) data.getTotalElements(), couponDetailVOList);
                return ServerResponse.createBySuccess(pageVO);
            }
        }
        return ServerResponse.createByErrorMsg("没有数据");
    }

    @ApiOperation("微信优惠券售卖明细")
    @PostMapping("/wxdetail/list")
    public ResultModel listWXDetail(@CurrentAdmin Long userId,@RequestBody WXCouponDetailRO ro) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId) ,ro.getMerchantStoreIds());
        PageVO pageVO = adminCouponService.listWXCouponDetail(ro,merchantStoreIdList, false);
        return ResultModel.ok().put("pageVO",pageVO);
    }

    @ApiOperation("导出微信优惠券售卖明细")
    @PostMapping("/wxdetail/export")
    public void exportWXDetail(@CurrentAdmin Long userId,@RequestBody WXCouponDetailRO ro, HttpServletResponse resp) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId) ,ro.getMerchantStoreIds());
        List<WXCouponDetailVO> wxCouponDetailVOList = adminCouponService.exportWXCouponDetail(ro,merchantStoreIdList);
        if (CollectionUtils.isNotEmpty(wxCouponDetailVOList)) {
            int index = 0;
            for (WXCouponDetailVO wxCouponDetailVO : wxCouponDetailVOList) {
                wxCouponDetailVO.setIndex( ++index );
            }
            String title = String.format("优惠券售卖明细报表");
            ExcelReportUtils.exportExcel(wxCouponDetailVOList,title,"优惠券售卖明细报表",WXCouponDetailVO.class,title+".xls",resp);
        }
    }

    @ApiOperation("微信优惠券售卖汇总")
    @PostMapping("/wxtotal/list")
    public ResultModel listWXTotal(@CurrentAdmin Long userId,@RequestBody WXCouponTotalRO ro) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId) ,ro.getMerchantStoreIds());
        PageVO<WXCouponTotalVO> pageVO = adminCouponService.listWXCouponTotal(ro,merchantStoreIdList,false);
        if(CollectionUtils.isNotEmpty(pageVO.getRecordList())){
            return ResultModel.ok().put("pageVO",pageVO);
        }
        return ResultModel.error("没有数据");
    }

    @ApiOperation("微信优惠券售卖汇总")
    @PostMapping("/wxtotal/export")
    public void exportWXTotal(@CurrentAdmin Long userId,@RequestBody WXCouponTotalRO ro, HttpServletResponse resp) {
        List<Long> merchantStoreIdList = Lists.newArrayList();
        merchantStoreIdList = QueryUtils.getMerchantIds(userService.findById(userId) ,ro.getMerchantStoreIds());
        List<WXCouponTotalVO> wxCouponTotalVOList = adminCouponService.exportWXCouponTotal(ro,merchantStoreIdList);
        if (CollectionUtils.isNotEmpty(wxCouponTotalVOList)) {
            int index = 0;
            for (WXCouponTotalVO wxCouponTotalVO : wxCouponTotalVOList) {
                wxCouponTotalVO.setIndex( ++index );
            }
            String title = String.format("微信优惠券售卖汇总");
            ExcelReportUtils.exportExcel(wxCouponTotalVOList,title,"微信优惠券售卖汇总",WXCouponTotalVO.class,title+".xls",resp);
        }
    }

}
